package com.wangzhixuan.apiController;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.InputFormatException;
import it.sauronsoftware.jave.MultimediaInfo;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wangzhixuan.commons.base.ApiBaseController;
import com.wangzhixuan.commons.constant.ApiCode;
import com.wangzhixuan.commons.constant.Constants;
import com.wangzhixuan.commons.scan.MyException;
import com.wangzhixuan.mapper.MeetingMapper;
import com.wangzhixuan.model.BaseInfo;
import com.wangzhixuan.model.Meeting;
import com.wangzhixuan.model.Recordings;
import com.wangzhixuan.model.VisitRecordings;
import com.wangzhixuan.model.vo.MeetingVo;
import com.wangzhixuan.service.IBaseInfoService;
import com.wangzhixuan.service.IMeetingService;
import com.wangzhixuan.service.IPeopleWorkService;
import com.wangzhixuan.service.IRecordingsService;
import com.wangzhixuan.service.IVisitRecordingsService;

/**
 * <p>
 *   前端控制器
 * </p>
 * @author zhixuan.wang
 * @since 2017-07-15
 */
@Controller
@RequestMapping("/api/meeting")
public class MeetingApiController extends ApiBaseController {
	
	
	@Autowired private IMeetingService meetingService;

	@Autowired private IRecordingsService recordingsService;
	
	@Autowired private IBaseInfoService baseInfoService;
	
	@Autowired private IPeopleWorkService peopleWorkService;
	
	@Autowired private IVisitRecordingsService visitRecordingsService;
	
	@Autowired
    private MeetingMapper meetingMapper;
	
	/**
	 * 开始会议
	 * @param meetingVo
	 * @return
	 * @throws MyException
	 */
	@RequestMapping("/new")
	@ResponseBody
	public Object creatMeeting(MeetingVo meetingVo) throws MyException{
		meetingVo.checekParam();
		Meeting meeting = meetingService.selectMeetingByUW(meetingVo.getWorkId());
	    if(meeting==null){
/*	    	if("12".equals(meetingVo.getMeeting())){
	    		return renderError(ApiCode.CODE_500, "请先创建班前会议");
	    	}*/
	    	Meeting meeting2 = new Meeting();
	    	meeting2.setUserId(meetingVo.getUserId());
			meeting2.setWorkId(meetingVo.getWorkId());
			meeting2.setType(meetingVo.getMeeting());
			meeting2.setCreateTime(new Date());
			meeting2.setStatus("22"); //21.未开始22.进行中23.结束
			boolean b = meetingService.insert(meeting2);
	        if (b) {
	        	BaseInfo baseInfo = baseInfoService.selectById(meetingVo.getWorkId());
	        	if("11".equals(meetingVo.getMeeting())){
	        		baseInfo.setStatus(Constants.WORK_STATUS.STATUS3);
	        		boolean c = baseInfoService.updateById(baseInfo);
	        		if(c){
	        			return renderSuccess(ApiCode.CODE_200, "成功");
	        		}
	        	}
	        	if("12".equals(meetingVo.getMeeting())){
	        			return renderSuccess(ApiCode.CODE_200, "成功");
	        	}
	        } else {
	        	return renderError(ApiCode.CODE_500, "添加失败");
	        }
	    }
	    if(meeting!=null){
    		if("11".equals(meeting.getType())&&"12".equals(meetingVo.getMeeting())){  //如果现在是班前会议，想创建班后
    			if("11".equals(meeting.getType())&&"22".equals(meeting.getStatus()))  //如果班前会议正在执行
    			{
    				return renderError(ApiCode.CODE_500, "请结束班前会议");
    			}
    			else																
    			{
    				meeting.setType("12");
        			meeting.setStatus("22");
        			meetingService.updateById(meeting);
        			return renderSuccess(ApiCode.CODE_200, "成功");
    			}
    		}	
		    if("22".equals(meeting.getStatus())){
		    	return renderError(ApiCode.CODE_201, "会议已存在");
		    }
		    if(meeting.getStatus().equals("23")){
		    	return renderError(ApiCode.CODE_202, "会议已结束");
		    }
		    else{
		    	return renderError(ApiCode.CODE_500, "操作错误");
		    }
	    }
	    else{
	    	return renderError(ApiCode.CODE_500, "操作错误");
	    }
	}
	
	/**
	 * 结束会议
	 * @param meetingVo
	 * @return
	 * @throws MyException
	 */
	@RequestMapping("/end")
	@ResponseBody
	public Object endMeeting(MeetingVo meetingVo) throws MyException{
		meetingVo.checekParam();
		Meeting meeting = meetingService.selectMeeting(meetingVo.getWorkId(),meetingVo.getMeeting());
    	if(meeting==null){
    		throw new MyException(ApiCode.CODE_500, "会议不存在");
    	}
    	if("23".equals(meeting.getStatus())){
    		throw new MyException(ApiCode.CODE_505, "没有权限操作");
    	}
    	if("22".equals(meeting.getStatus())){
    		meeting.setStatus("23");
            boolean b = meetingService.updateById(meeting);
    		if (b) {
            	return renderSuccess(ApiCode.CODE_200, "成功");
            } else {
            	return renderError(ApiCode.CODE_500, "操作失败");
            }
    	}
    	else {
        	return renderError(ApiCode.CODE_500, "操作失败");
        }
	}
	
	/**
	 * 上传会议录音
	 * @param userId
	 * @param workId
	 * @param meeting
	 * @param recordings
	 * @param request
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws MyException
	 * @throws InputFormatException
	 * @throws EncoderException
	 */
	@RequestMapping("/add")
    @ResponseBody
    public Object add(String userId,String workId,String meeting,String recordings,String recordTime,HttpServletRequest request) throws IllegalAccessException, InvocationTargetException, MyException, InputFormatException, EncoderException {
    	
    	if(userId == null || userId.length() <= 0) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
        }
    	if (workId == null || workId.length() <= 0) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
    	if (meeting == null || meeting.length() <= 0) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
    	if (recordings == null || recordings.length() <= 0) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
    	Meeting meet = meetingService.selectMeeting(workId,meeting);
    	if(meet==null){
    		throw new MyException(ApiCode.CODE_500, "会议不存在");
    	}
    	Integer meetId = meet.getId();
    	/*File source = new File("C:\\KuGou\\test.mp3"); 本地测试成功*/
    /*	File source = new File(getRootPath()+recordings.replace(getbaseUrl(request),""));
    	Encoder encoder = new Encoder();
        MultimediaInfo m = encoder.getInfo(source);
        long ls = m.getDuration();				
    	Long ls = new Long(0);
    	System.out.println("此视频时长为:" + ls / 60000 + "分" + ls / 1000 + "秒！");*/
        Recordings recording = new Recordings();
        recording.setCreatTime(new Date());
        recording.setFailPath(recordings);
        recording.setRecordingsLength(recordTime);
        recording.setUserId(Integer.valueOf(userId));
        recording.setMeetingId(meetId);
        recording.setMeetType(Integer.valueOf(meeting));
        boolean b = recordingsService.insert(recording);
        if (b) {
        	return renderSuccess(ApiCode.CODE_200, "成功");
        } 
        else {
        	return renderError(ApiCode.CODE_500, "添加失败");
        }
    }
	
	@RequestMapping("/detailed")
    @ResponseBody
    public Object detailed(Integer userId,Integer workId,String meeting) throws MyException {
		
	/*	List<Integer> users = peopleWorkService.selectUser(workId);
		for(int i=0;i<users.size();i++){
			Meeting meeting2 = meetingService.selectMeetingByUW(users.get(i).toString(),workId.toString());
			if(meeting2!=null){
				return renderSuccess(ApiCode.CODE_200, "会议已经创建");
			}
		}
		*/
		//Meeting meeting2 = meetingService.selectMeetingByUW(workId.toString());  //判断会议是否存在
    	if(userId==null){
			 throw new MyException(ApiCode.CODE_501, "请重新登录");
		}
		if(workId==null){
			 throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
		}
		if (meeting == null || meeting.length() <= 0) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("userId", userId);
		paramMap.put("workId", workId);
		paramMap.put("meeting", meeting);
		Map<String, Object> selectRecordings = recordingsService.selectRecordings(userId, workId, meeting);
		Meeting meeting2 = meetingMapper.selectMeetForStatus(paramMap);
		int meetingId = 0;
		if(meeting2!=null){
			meetingId = meeting2.getId();
		}
		VisitRecordings visitRecordings = new VisitRecordings();
		visitRecordings.setMeetingType(Integer.valueOf(meeting));
		visitRecordings.setMeetingId(meetingId);
		visitRecordings.setWorkId(workId);
		visitRecordings.setUserId(userId);
		visitRecordings.setVisitTime(new Date());
		visitRecordingsService.insert(visitRecordings);		//添加访问时间
		return renderSuccess(ApiCode.CODE_200, "成功",selectRecordings);
    }
	
	
	@RequestMapping("/getStatus")
	@ResponseBody
	public Object getStatus(Integer workId,Integer userId) throws MyException{
	   	if(userId == null ) {
				throw new MyException(ApiCode.CODE_501, "请重新登录");
	        }
	    if (workId == null ) {
				throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
	        }
	    Map<String,Object> map = new HashMap<String,Object>();
		Meeting meeting = meetingService.selectMeetForBase(userId, workId);   //在后来的版本中去掉了userId,实际只用了workId查询
		if(meeting!=null)
		{
			if("11".equals(meeting.getType())){
				map.put("afterMeeting","301"); //301未开始302进行中303结束
				if("21".equals(meeting.getStatus())){
					map.put("frontMeeting", "301");
				}
				if("22".equals(meeting.getStatus())){
					map.put("frontMeeting", "302");
				}
				if("23".equals(meeting.getStatus())){
					map.put("frontMeeting", "303");
				}
			}
			if("12".equals(meeting.getType())){
				map.put("frontMeeting", "303");
				if("21".equals(meeting.getStatus())){
					map.put("afterMeeting", "301");
				}
				if("22".equals(meeting.getStatus())){
					map.put("afterMeeting", "302");
				}
				if("23".equals(meeting.getStatus())){
					map.put("afterMeeting", "303");
				}
			}
		}
		else{
			map.put("afterMeeting","301");
			map.put("frontMeeting","301");
		}
		return renderSuccess(ApiCode.CODE_200, "成功",map);
	}
	
	@RequestMapping("/visit")
    @ResponseBody
    public Object visit(Integer userId,Integer workId,String meeting,Date nowTime) throws MyException, ParseException {
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//nowTime = sdf.parse("2017-09-22 12:10:12");			//死数据
    	if(userId==null){
			 throw new MyException(ApiCode.CODE_501, "请重新登录");
		}
		if(workId==null){
			 throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
		}
		if (meeting == null || meeting.length() <= 0) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("workId", workId);
		Meeting meeting2 = meetingMapper.selectMeetForStatus(paramMap);
		if(meeting2!=null){
			int meetingId = 0;
			meetingId = meeting2.getId();
			Date visitTime = visitRecordingsService.selectVisitTime(workId,meeting,userId);
			//visitTime = sdf.parse("2017-09-01 12:10:12");			//死数据
			List<Map<String,Object>> list = recordingsService.selectVisitRecordings(userId,meetingId, meeting, nowTime, visitTime);
			VisitRecordings visitRecordings = new VisitRecordings();					//查询完了以后
			visitRecordings.setMeetingType(Integer.valueOf(meeting));
			visitRecordings.setMeetingId(meetingId);
			visitRecordings.setWorkId(workId);
			visitRecordings.setUserId(userId);
			visitRecordings.setVisitTime(nowTime);
			visitRecordingsService.insert(visitRecordings);		//添加访问时间
			return renderSuccess(ApiCode.CODE_200, "成功",list);
		}
		return renderError(ApiCode.CODE_500, "获取语音时要保持网络稳定哦！");
    }
	
}
